package fastdht

import (
	log "github.com/golang/glog"
	"net"
)

const (
	maxUDPPacketSize = 4096
)

func listen(address *net.UDPAddr) (conn *net.UDPConn, e error) {

	conn, err := net.ListenUDP("udp4", address)
	if err != nil {
		log.Fatal(err)
	}
	log.V(5).Infof("DHT开始监听，IP:%s,Port:%d", address.IP.String(), address.Port)
	return
}
func sendMsg(conn *net.UDPConn, address *net.UDPAddr, query interface{}) {
	b, err := encodeMsg(query)
	if err != nil {
		return
	}

	if _, err := conn.WriteToUDP(b, address); err != nil {
		log.V(3).Infof("DHT:node write failed to %+v, error=%s", address, err)
	} else {
		log.V(3).Infof("发送成功UDP数据包,IP：%s,Port:%d", address.IP.String(), address.Port)
	}
	return
}

//
func reviceMsg(conn *net.UDPConn, packetChan chan packetType) {
	//	这个函数有三个参数，一个是socket 连接，一个是通道
	for {
		b := make([]byte, maxUDPPacketSize)
		n, addr, err := conn.ReadFromUDP(b)
		if err != nil {
			log.V(3).Infof("DHT: readResponse error:", err)
			continue
		}
		b = b[0:n]
		if n == maxUDPPacketSize {
			log.V(3).Infof("DHT: Warning. Received packet with len >= %d, some data may have been discarded.\n", maxUDPPacketSize)
		}

		if n > 0 && err == nil {
			p := packetType{b, addr}

			select {
			case packetChan <- p:
				continue
			default:
				continue
			}
		}
	}
}

//func sendFindNode(conn *net.UDPConn, address *net.UDPAddr) {
//	query := new(queryMessage)
//
//	tid := tranId()
//	target := randNodeId().String()
//	nid := randNodeId()
//}
